package es.udc.emarketapp.emarket.model.shippingFacade.actions;

import es.udc.emarketapp.emarket.model.country.vo.CountryVO;
import es.udc.emarketapp.emarket.model.countryFacade.CountryFacade;
import java.sql.Connection;
import java.util.List;

import es.udc.emarketapp.emarket.model.shipping.dao.SQLShippingDAO;
import es.udc.emarketapp.emarket.model.shipping.dao.SQLShippingDAOFactory;
import es.udc.emarketapp.emarket.model.shipping.vo.ShippingVO;
import es.udc.emarketapp.emarket.model.shippingFacade.vo.ShippingsCountryVO;
import es.udc.fbellas.j2ee.util.exceptions.InstanceNotFoundException;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.NonTransactionalPlainAction;
import java.util.ArrayList;
import java.util.Iterator;

public class CountryRatesAction implements NonTransactionalPlainAction {

    private String idSeller;
    private String idCountry;
    private String language;

    public CountryRatesAction(String idSeller, String idCountry, String language) {

        this.idSeller = idSeller;
        this.idCountry = idCountry;
        this.language = language;
    }

    public Object execute(Connection connection)
            throws InternalErrorException {


        SQLShippingDAO shippingDAO = SQLShippingDAOFactory.getDAO();

        List<ShippingVO> shippingVOs = shippingDAO.findRates(connection,
                idSeller, idCountry, 1, 10);

        List<Double> weightRanges = new ArrayList();
        List<Double> priceRanges = new ArrayList();

        Iterator iter = shippingVOs.iterator();

        ShippingVO shipping;
        while (iter.hasNext()) {
            shipping = (ShippingVO) iter.next();
            weightRanges.add(shipping.getPeso());
            priceRanges.add(shipping.getPrecio());
        }

        CountryFacade countryFacade = new CountryFacade();
        CountryVO country = null;
        try {
             country = countryFacade.findById(idCountry, language);
        } catch (InstanceNotFoundException e) {
            throw new InternalErrorException(e);
        }

            return new ShippingsCountryVO(idSeller, idCountry, country.getNomPais(), weightRanges, priceRanges);

        }
    }
